package com.lcq.httplib.parser;

import android.util.Log;

import com.google.gson.Gson;
import com.lcq.httplib.ErrorEnum;
import com.lcq.httplib.callback.DataCallback;

import org.json.JSONArray;
import org.json.JSONObject;

public class CommonDataParser<T> implements DataParser<T> {
    @Override
    public void parse(String content, DataCallback<T> callback) {
        try {
            Log.d("http", "client.content:" + content);
            JSONObject textJson = new JSONObject(content);
            int code = textJson.optInt("code");
            String msg = textJson.optString("msg");
            JSONObject data = textJson.optJSONObject("data");

            if (code != ErrorEnum.SUCCESS.getCode()) {
                callback.onFail(code, msg);
                return;
            }

            T result = null;
            if (data != null) {
                if (JSONObject.class.equals(callback.getDataType()) || JSONArray.class.equals(callback.getDataType())) {
                    result = (T) data;
                } else {
                    result = new Gson().fromJson(data.toString(), callback.getDataType());
                }
            }
            callback.onSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            callback.onFail(ErrorEnum.PARSE_FAIL.getCode(), ErrorEnum.PARSE_FAIL.getMsg());
        }
    }
}
